package com.example.demo.io;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket();
        serverSocket.bind(new InetSocketAddress(9999));

        System.out.println("Server start listen port=" + serverSocket.getLocalPort());

        Socket socket = serverSocket.accept();

        System.out.println("Server accept socket, ip=" + socket.getRemoteSocketAddress());
        DataInputStream in = new DataInputStream(socket.getInputStream());
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        int a1 = in.available();
        System.out.println("in.available(): " + a1);
        int totalLength = in.readInt();
        System.out.println("in.totalLength: " + totalLength);
        /**
         * b - 存储读取数据的缓冲区。
         * off - 目标数组 b 中的起始偏移量
         * len - 读取的最大字节数。
         */
        byte[] bytes = new byte[totalLength-4];
        int readCount = 0;
        while (readCount < totalLength-4) {
            int temp = in.read(bytes, readCount, totalLength - 4 - readCount);
            System.out.println("每次读取字节数：" + temp);
            readCount += temp;
        }
        System.out.println(new String(bytes));

    }
}
